package com.github.permissiondog.cancanpandroid.ui.view;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import com.github.permissiondog.cancanpandroid.R;
import com.github.permissiondog.cancanpandroid.databinding.ActivitySelectCourseBinding;
import com.github.permissiondog.cancanpandroid.model.Application;
import com.github.permissiondog.cancanpandroid.model.TableTemplate;
import com.github.permissiondog.cancanpandroid.repository.impl.ApplicationRepositoryImpl;
import com.github.permissiondog.cancanpandroid.repository.impl.ImageRepositoryImpl;
import com.github.permissiondog.cancanpandroid.repository.impl.TemplateRepositoryImpl;
import com.github.permissiondog.cancanpandroid.util.Constants;

import java.io.IOException;

public class SelectCourseActivity extends AppCompatActivity {

    private ActivityResultLauncher<String> resultLauncher;
    private String imageSha;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivitySelectCourseBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_select_course);

        var adapter = new ArrayAdapter<TableTemplate>(this, android.R.layout.simple_spinner_item);
        var tempTemplate = new TableTemplate();
        tempTemplate.setTableName("占位");
        adapter.add(tempTemplate);
        TemplateRepositoryImpl.getInstance().getSelectableTemplates(templates -> runOnUiThread(() -> {
            adapter.clear();
            adapter.addAll(templates);
        }));
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        binding.spinnerCourses.setAdapter(adapter);

        resultLauncher = registerForActivityResult(new ActivityResultContracts.GetContent(), result -> {
            Log.d("ImageUpload", result.toString());
            Bitmap bitmap;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), result);
            } catch (IOException e) {
                Toast.makeText(this, "读取图片失败: " + result.toString(), Toast.LENGTH_LONG).show();
                Log.e("ImageUpload", "读取文件失败", e);
                return;
            }
            binding.ivImageUploaded.setImageBitmap(bitmap);

            ImageRepositoryImpl.getInstance().uploadImage(bitmap, res -> {
                Log.d("ImageUpload", "上传成功: " + res.getSha());
                imageSha = res.getSha();
            });
        });
        binding.btnUploadImage.setOnClickListener(l -> {
            resultLauncher.launch("image/*");
        });
        binding.btnSubmitSelectCourse.setOnClickListener(l -> {
            if (binding.spinnerCourses.getSelectedItemPosition() == -1) {
                Toast.makeText(this, "请先选择课程", Toast.LENGTH_LONG).show();
                return;
            }
            var template = (TableTemplate) binding.spinnerCourses.getSelectedItem();
            if (binding.etReason.getText().toString().equals("")) {
                Toast.makeText(this, "请先填写申请原因", Toast.LENGTH_LONG).show();
                return;
            }
            if (imageSha == null) {
                Toast.makeText(this, "请先上传证明", Toast.LENGTH_LONG).show();
                return;
            }
            ApplicationRepositoryImpl.getInstance().createApplication(
                    template.getId(), binding.etReason.getText().toString(), imageSha,
                    res -> {
                        var intent = new Intent();
                        intent.setAction(Constants.ACTION_REFRESH_APPLICATIONS);
                        sendBroadcast(intent);
                        Toast.makeText(this, "提交申请成功", Toast.LENGTH_LONG).show();
                        finish();
                    });

        });
    }
}